package com.neusoft.elmboot.controller;

import com.neusoft.elmboot.po.Business;
import com.neusoft.elmboot.po.Star;
import com.neusoft.elmboot.service.StarService;
import com.neusoft.elmboot.service.ex.DataNotFoundException;
import com.neusoft.elmboot.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/stars")
public class StarController {
    public static final int OK = 200;
    public static final int ERROR = 500;
    public static final int DATA_NOT_FOUND = 204;

    @Autowired
    private StarService starService;

    @PostMapping
    public JsonResult<Star> createStar(@RequestBody Star star) throws Exception{
        JsonResult<Star> result = new JsonResult<>();
        if (star == null) {
            result.setState(DATA_NOT_FOUND);
            result.setMessage("传过来的收藏数据不能为空！");
            return result;
        }
        try {
            int data = starService.insertStar(star);
            result = new JsonResult<>(OK, star);
            result.setMessage("收藏成功");
            return result;
        }catch (DataNotFoundException e) {
            result.setState(DATA_NOT_FOUND);
            result.setMessage(e.getMessage());
            return result;
        }catch(Exception e) {
            result.setState(ERROR);
            result.setMessage(e.getMessage());
            return result;
        }
    }

    @DeleteMapping
    public JsonResult<Star> deleteStar(@RequestBody Star star) throws Exception{
        JsonResult<Star> result = new JsonResult<>();
        if (star == null) {
            result.setState(DATA_NOT_FOUND);
            result.setMessage("传过来的收藏数据不能为空！");
            return result;
        }
        try {
            int data = starService.deleteStar(star);
            result = new JsonResult<>(OK, star);
            result.setMessage("取消收藏成功");
            return result;
        }catch (DataNotFoundException e) {
            result.setState(DATA_NOT_FOUND);
            result.setMessage(e.getMessage());
            return result;
        }catch(Exception e) {
            result.setState(ERROR);
            result.setMessage(e.getMessage());
            return result;
        }
    }

    @GetMapping("/{userId}")
    public JsonResult<List<Business>> findStarsByUserId(@PathVariable String userId) {
        JsonResult<List<Business>> result = new JsonResult<List<Business>>();
        try {
            List<Business> data = starService.findStarsByUserId(userId);
            result = new JsonResult<List<Business>>(OK, data);
            result.setMessage("获取收藏成功");
            return result;
        }catch (DataNotFoundException e) {
            result.setState(DATA_NOT_FOUND);
            result.setMessage(e.getMessage());
            return result;
        }
    }
}
